<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/11/9 0009
 * Time: 下午 2:39
 */
namespace app\api\controller;
use think\Loader;
use think\Request;

class Question extends App
{


    /**
     * 测评列表
     */
    public function index()
    {
		$cat = db('ceping_cat')->field('id,name')->where('is_show',1)->order('sort asc')->select();
		foreach ($cat as $kk => $vv)
		{
			$question_list = db('ceping')->field('id,name,question_remark,cover,cp_num,cp_time')->where('is_show',1)->where('cat_id',$vv['id'])->order('sort asc')->select();
			
			$question_list = array_map(function ($rs){
				$rs['cover'] = str_replace("\\","/",config('app_host').$rs['cover']);
				$rs['question_nums'] = db('ceping_question')->where('is_show',1)->where('cp_id',$rs['id'])->count();
				return $rs;
			}, $question_list);	
			$cat[$kk]['ceping_list'] = $question_list;	
			
		}
        return $this->show(1,"success", $cat);
    }

    /**
     * 获取题目详情
     */
    public function get_detail()
    {
        $ceping_id = input('ceping_id');
        if(!$ceping_id) return $this->show(2001,'缺少参数question_id');
        $info = db('ceping')->field('id,name,question_remark,cover,cp_num,cp_time,question_content')->where('id',$ceping_id)->where('is_show',1)->order('sort asc')->find();
		$info['cover'] = str_replace("\\","/",config('app_host').$info['cover']);
		$info['question_nums'] = db('ceping_question')->where('is_show',1)->where('cp_id',$info['id'])->count();
		
		$ceping_log = db('ceping_log')->where('cp_id',$ceping_id)->where('uid',$this->user_id)->value('id');
		$info['is_finish'] = !empty($ceping_log)?1:0; 
		$other_list = db('ceping')->field('id,name,cover')->where('is_show',1)->where('id','<>',$ceping_id)->order('RAND()')->limit(4)->select();
		$other_list = array_map(function ($rs){
				$rs['cover'] = str_replace("\\","/",config('app_host').$rs['cover']);
				return $rs;
			}, $other_list);	
		$info['other_list'] = $other_list;
        return $this->show(1,"success", $info);
    }
	
	//开始测评
    public function get_question_list()
    {
        $ceping_id = input('ceping_id');
        $where = ['is_show'=>1];
        if(!$ceping_id) return $this->show(2001,'缺少参数question_id');
		
		
        $info = db('ceping')->field('id,name,algorithm')->where('id',$ceping_id)->where('is_show',1)->order('sort asc')->find();
        if(empty($info)) return $this->show(2001,'测评不存在');
		
        
        
		$list = db('ceping_question')->field('id,title,options')->where('cp_id',$ceping_id)->where('is_show',1)->order('sort asc')->select();
		$list_new = [];
		foreach ($list as $kk => $vv)
		{
			$options_arr = json_decode($vv['options'],true);
			$options = array_column($options_arr,'title');
			
			$list_new[$kk] = ['id'=>$vv['id'],'title'=>$vv['title'],'option'=>$options];
			
		}
		
        return $this->show(1,"success", $list_new);
    }
	
    public function finish_question()
    {
		/*$a = '{';
		for($i=423;$i<=427;$i++){
			$a.='"'.$i.'":3,';
		}
		$a .= '}';
		echo $a;die;*/
		
        $ceping_id = input('ceping_id');
        $order_id = input('order_id');
        if(!$ceping_id) return $this->show(2001,'缺少参数ceping_id');
		$answers = input('answers');
        if(!$answers) return $this->show(2001,'缺少参数answers');
		$answer_arr = json_decode($answers,true);
        if(empty($answer_arr)) return $this->show(2001,'请先作答');
      
        $info = db('ceping')->field('id,name,ceping_type,score_options,score_group_pics')->where('id',$ceping_id)->where('is_show',1)->order('sort asc')->find();
        if(empty($info)) return $this->show(2001,'测评不存在');
		
		//调用算法
        //$QuestionService = service("ceping\\".$info['algorithm']);
		//$result = $QuestionService->calculateScore($answer_arr);
		//$result_json = json_encode($result,JSON_UNESCAPED_UNICODE);
		
		$QuestionService = service("ceping\\CommonService");
		$result = $QuestionService->calculateScore($answer_arr,$info);
		if($result['code'] != 1){
			return $this->show(2001,$result['msg']);
		}
		$result_json = json_encode($result['data'],JSON_UNESCAPED_UNICODE);
		
		$ceping_log = db('ceping_log')->where('cp_id',$ceping_id)->where('uid',$this->user_id)->field('id,order_id')->find();
		if(!empty($ceping_log)){
			if(empty($order_id) && !empty($ceping_log['order_id'])){
				$order_id = $ceping_log['order_id'];
			}
			$dataU = ['title'=>$info['name'],'ceping_type'=>$info['ceping_type'],'answers'=>$answers,'result_json'=>$result_json,'order_id'=>$order_id,'update_time'=>time()];
			if($info['ceping_type'] == 1){
				$dataU['score_total'] = $result['data']['score_total'];
			}else{
				$dataU['weidu_json'] =json_encode($result['data']['weidu_list_new'],JSON_UNESCAPED_UNICODE);;
			}
			$dataU['score_title'] = $result['data']['score_title'];
			$dataU['score_info'] = $result['data']['score_info'];
			$dataU['score_pic'] = $result['data']['score_pic'];
			$flag = Db('ceping_log')->where('id',$ceping_log['id'])->update($dataU);
			$ceping_red_id = $ceping_log['id'];
		}else{
			$dataI = ['uid'=>$this->user_id,'cp_id'=>$ceping_id,'ceping_type'=>$info['ceping_type'],'title'=>$info['name'],'answers'=>$answers,'result_json'=>$result_json,'order_id'=>$order_id,'create_time'=>time(),'update_time'=>time()];
			if($info['ceping_type'] == 1){
				$dataI['score_total'] = $result['data']['score_total'];
			}else{
				$dataI['weidu_json'] =json_encode($result['data']['weidu_list_new'],JSON_UNESCAPED_UNICODE);;
			}
			$dataI['score_title'] = $result['data']['score_title'];
			$dataI['score_info'] = $result['data']['score_info'];
			$dataI['score_pic'] = $result['data']['score_pic'];
			$flag = Db('ceping_log')->insertGetId($dataI);
			$ceping_red_id = $flag;
		}
		if($info['ceping_type'] == 2 || $info['ceping_type'] == 3 || $info['ceping_type'] == 5 || $info['ceping_type'] == 4 || $info['ceping_type'] == 6){
			$weidu_list_new = $result['data']['weidu_list_new'];
			Db('ceping_log_weidu')->where('cp_id',$ceping_id)->where('uid',$this->user_id)->where('cp_red_id',$ceping_red_id)->delete();
			$dataW = [];
			foreach($weidu_list_new as $k=>$v){
				$dataW[] = ['ceping_type'=>$info['ceping_type'],'uid'=>$this->user_id,'cp_id'=>$ceping_id,'cp_red_id'=>$ceping_red_id,'title'=>$v['title'],'weidu_id'=>$v['weidu_id'],'score_total'=>$v['score_total'],'score_title'=>$v['score_title'],'score_info'=>$v['score_info'],'create_time'=>time(),'update_time'=>time()];
			}
			if(!empty($dataW)){
				Db('ceping_log_weidu')->insertAll($dataW);
			}
		}
		
		
		if($flag){
			//$data_return = ['ceping_id'=>$ceping_id,'ceping_red_id'=>$flag,'cp_result'=>$result];
			$data_return = ['ceping_id'=>$ceping_id,'ceping_red_id'=>$ceping_red_id];
			return $this->show(1,"success",$data_return);
		}else{
			return $this->show(2002,'接口出错');
		}
    }
	
    public function get_result()
    {
        $ceping_id = input('ceping_id');
        $ceping_red_id = input('ceping_red_id');
		$user_id = $this->user_id;
        if(empty($ceping_id) && empty($ceping_red_id)) return $this->show(2001,'缺少参数ceping_id或ceping_red_id');
		
		if(!empty($ceping_red_id)){
			$info = db('ceping_log')->field('id,title,cp_id,ceping_type,score_total,score_title,score_info,result_json,update_time,score_pic,weidu_json')->where('id',$ceping_red_id)->where('uid',$user_id)->find();
		}else{
			$info = db('ceping_log')->field('id,title,cp_id,ceping_type,score_total,score_title,score_info,result_json,update_time,score_pic,weidu_json')->where('cp_id',$ceping_id)->where('uid',$user_id)->find();
		}
        if(empty($info)) return $this->show(2001,'您还未测评');
		
		$QuestionService = service("ceping\\CommonService");
		$result = $QuestionService->getCalculateResult($info);
		if($result['code'] != 1){
			return $this->show(2001,$result['msg']);
		}
		
        return $this->show(1,"success", $result['data']);
    }
	
    public function zonghe_start()
    {
        $return_data['my_progress'] = 80;
        $return_data['platform_progress'] = 80;
		$return_data['content'] = '<p>1、明德平台上所有测评由北大、北师大、南师大心理和职业生涯规划领域教授、专家根据专业理论结合本土化特点编制而成；</p><p>2、测评结果会受到多种因素的影响，如作答题目的认真程度、当前个人的状态等等；</p><p>3、职业推荐根据研究结果得出，但由于社会、学校、家庭等因素的影响，以及对自我的认知并不全面等原因，部分职业可能和自己的第一感觉不相符，建议将此类职业纳入考虑范围，在实践中进行检验后再决定取舍；</p><p>4、心理测评结果具有阶段性和发展性，本测评报告仅能代表现阶段个人的状态，测试结论用作他处请慎重，并请咨询专业人士；
</p><p>5、综合报告内所有测评结果均根据你最近一次测评分数得出。</p>';
        return $this->show(1,"success", $return_data);
    }
	
    public function get_zonghe_cate()
    {
        $list = db('ceping_cat')->field('id,name')->where('is_show',1)->select();
        return $this->show(1,"success", $list);
    }
		
    public function get_zonghe_baogao()
    {
		$user_id = $this->user_id;
        $cate_id = input('cate_id');
        if(!$cate_id) return $this->show(2001,'缺少参数cate_id');
        $ceping_cat = db('ceping_cat')->where('id',$cate_id)->where('is_show',1)->find();
        if(empty($ceping_cat)) return $this->show(2001,'分类不存在');
		
		$QuestionService = service("ceping\\CommonService");
		$result = $QuestionService->getSingleZongheBaogao($ceping_cat,$user_id);
        if($result['code'] != 1){
			return $this->show(2001,$result['msg']);
		}
		
        return $this->show(1,"success", $result['data']);
    }
	
    public function get_zonghe_baogao_jobs()
    {
		$user_id = $this->user_id;
		$job_tuijian = [];
		$job_xingqu = db("member_ceping_xingqu_job")->field('id,job_title')->where('user_id',$user_id)->group('job_title')->select();
		$score_info = '<p>1、通过测评总结自己的特质：人格特点、兴趣/价值观偏好、能力优势/劣势等；</p><p>2、找一张纸列出测评推荐的职业和其他未推荐但你感兴趣的职业，形成你的职业清单（career list）；</p><p>3、将清单中的职业按某个标准进行排序，如感兴趣程度、薪酬水平等，查看自己所从事的职业是否在其中；</p><p>4、对照自己的特质，试着规划职业生涯，思考是否转换职业方向，或在当前的职业中加强自身的职业技能；</p><p>5、可与身边朋友、职场前辈或专业咨询师讨论你的职业清单，多方收集意见。</p>';
		$return_data = ['job_tuijian'=>$job_tuijian,'job_xingqu'=>$job_xingqu,'score_info'=>$score_info];
        return $this->show(1,"success", $return_data);
    }
	
    public function get_job_lib()
    {
        $list = db('ceping_job_lib')->field('id,title')->where('is_show',1)->select();
        return $this->show(1,"success", $list);
    }
	
	public function add_xingqu_job()
    {
        $user_id = $this->user_id;
        if($this->request->isPost()){
			
			$job_id = $this->request->post("job_id",0,'intval');
			if (empty($job_id)) {
				return $this->show(2001,"缺少参数job_id!", '');
			}
			$job_info = db('ceping_job_lib')->field('id,title')->where('id',$job_id)->find();
			if (empty($job_info)) {
				return $this->show(2001,"职业不存在!", '');
			}
			
			$flag = db("member_ceping_xingqu_job")->where('user_id',$user_id)->where('job_id',$job_id)->value('id');
			if (!empty($flag)) {
				return $this->show(2001,"职业清单已存在该职业，不能重复添加!", '');
			}
			$data['job_id'] = $job_id;
			$data['job_title'] = $job_info['title'];
			$data['user_id'] = $user_id;
			$data['create_time'] = time();
			$res = db("member_ceping_xingqu_job")->insert($data);
			if( $res !== false ){
				return $this->show(1,"success", '');
			}else{
				return $this->show(2002, "fail", "");
			} 
		}else{
            return $this->show(2001, "非法请求", "");
        }
	}
	
	public function del_xingqu_job()
    {
        $user_id = $this->user_id;
        if($this->request->isPost()){
			
			$job_id = $this->request->post("job_id",0,'intval');
			if (empty($job_id)) {
				return $this->show(2001,"缺少参数job_id!", '');
			}
			$flag = db("member_ceping_xingqu_job")->where('user_id',$user_id)->where('job_id',$job_id)->delete();
			if( $flag !== false ){
				return $this->show(1,"success", '');
			}else{
				return $this->show(2002, "fail", "");
			} 
		}else{
            return $this->show(2001, "非法请求", "");
        }
	}
	//获取分类测评报告分类 
    public function get_category_cate()
    {
        $list = db('ceping_baogao_cat')->field('id,name')->where('is_show',1)->select();
		foreach($list as $k=>$v){
			$sub = db('ceping')->where('cat_id',$v['id'])->group('sub_category')->column('sub_category');
			$list[$k]['sub'] = array_filter($sub);
		}
        return $this->show(1,"success", $list);
    }
    public function get_category_cepings()
    {
        $user_id = $this->user_id;
		$cate_id = $this->request->get("cate_id",0,'intval');
		$sub_title = $this->request->get("sub_title",'','trim');
		$map['is_show'] = 1;
		if(!empty($cate_id)){
			$map['baogao_cat_id'] = $cate_id;
		}
		if(!empty($sub_title)){
			$map['sub_category'] = $sub_title;
		}
        /*$cp_ids = db('ceping')->where($map)->column('id');
		
		$list = db('ceping_log')->field('id as ceping_red_id,cp_id as ceping_id,title,update_time')->where('cp_id','in',$cp_ids)->where('uid',$user_id)->select();
		$list = array_map(function ($rs){
			$rs['update_time'] = date('Y-m-d',$rs['update_time']);
			return $rs;
		}, $list);	*/	
		$list = db('ceping')->field('id as ceping_id,name as title')->where($map)->select();
		foreach($list as $k=>$v){
			$ceping_log = db('ceping_log')->field('id,update_time')->where('uid',$user_id)->where('cp_id',$v['ceping_id'])->find();
			if(!empty($ceping_log)){
				$list[$k]['is_finish'] = 1;
				$list[$k]['ceping_red_id'] = $ceping_log['id'];
				$list[$k]['update_time'] = date('Y-m-d',$ceping_log['update_time']);
			}else{
				$list[$k]['is_finish'] = 0;
			}
		}
		
        return $this->show(1,"success", $list);
    }
	
}